<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card class="box-card">
      <!-- alert警告组件 -->
      <el-alert title="消息提示的文案" type="info" show-icon center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="Number(activeNum)" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form ref="goodsAddForm" :model="AddForm" label-width="150px" :rules="AddFormrules">
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeNum"
          :before-leave="beforeLeave"
          @tab-click="tabClick()"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="AddForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="AddForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="AddForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="sanjiCat">
              <el-cascader
                v-model="AddForm.sanjiCat"
                :options="jiInfo"
                :props="{
                  expandTrigger: 'hover',
                  label:'cat_name',
                  value:'cat_id'}"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数(动)" name="1">
            <el-form-item v-for="item in manyinfo" :key="item.attr_id" :lable="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals_arr">
                <el-checkbox
                  v-for="item2 in item.attr_vals_arr2"
                  :key="item2"
                  :label="item2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性(静)" name="2">
            <el-form-item v-for="item in onlyinfo" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:11333/api/private/v1/upload"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="AddForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 引入富文本编辑器相关配置
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  components: {
    quillEditor // quillEditor 和 quill-editor 一样
  },
  created () {
    this.getJiList()
  },
  data () {
    return {
      manyinfo: [], // 接收动态数据
      onlyinfo: [], // 接收静态数据
      // 给图片设置请求头
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      selectCatId: 0, // 接收级联选择器第3级分类的信息
      jiInfo: [], // 级联器上级数据来源
      tabPosition: 'left', // 设置tap标签的方向
      activeNum: '0', // 默认显示1
      AddForm: {
        goods_introduce: '',
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: '',
        sanjiCat: [], // 写在这里form可以重置校验 级联选择器 获取选中的项目 是数组形式[1,2,3] 表单校验
        pics: [], // 存上传图片的路径名
        attrs: [] // 收集参数 和其可选值 动 / 静
      },
      AddFormrules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        sanjiCat: [{ required: true, message: '请选择分类', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 添加商品事件
    addGoods () {
      this.$refs.goodsAddForm.validate(async valid => {
        if (valid) {
          // 处理动态的参数
          this.manyinfo.forEach(item => {
            //                  获得id           把数组变成字符串
            var objmany = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals_arr.join(' ')
            }
            this.AddForm.attrs.push(objmany) // 放到 AddForm 中
          })

          // 处理静态参数
          this.onlyinfo.forEach(item => {
            var objonly = { attr_id: item.attr_id, attr_value: item.attr_vals }
            this.AddForm.attrs.push(objonly) // 放到 AddForm 中
          })
          console.log(this.AddForm.attrs)

          var { data: dt } = await this.$http.post('goods', this.AddForm)
          this.$message.success(dt.meta.msg)
          this.$router.push('/goods') // 跳转到goods页面

          console.log(dt)
        } else {
          this.$message.error(dt.meta.msg)
        }
      })
    },
    // tab 被选中时触发 发送请求获得动 / 静  数据
    async tabClick () {
      // 获取三级分类的id
      var id = this.AddForm.sanjiCat[2]
      // console.log(this.activeNum, id)
      if (this.activeNum === '1') {
        // 说明是 动 发送获得动态参数请求
        var { data: dt } = await this.$http.get(
          'categories/' + id + '/attributes',
          { params: { sel: 'many' } }
        )
        // console.log(dt)
        // 处理数据 把字符串变成数组 可以用来遍历
        dt.data.forEach(item => {
          // 给复选框使用
          item.attr_vals_arr = item.attr_vals.split(' ')
          // 设定复选框选中的
          item.attr_vals_arr2 = item.attr_vals.split(' ')
        })
        // console.log(dt)
        this.manyinfo = dt.data
        // console.log(this.manyinfo)
      }
      if (this.activeNum === '2') {
        var { data: dt2 } = await this.$http.get(
          'categories/' + id + '/attributes',
          { params: { sel: 'only' } }
        )
        console.log(dt2, 2)
        this.onlyinfo = dt2.data
      }
    },
    // 图片上传成功的回调处理
    handleSuccess (success) {
      // console.log(success)
      if (success.meta.status !== 200) {
        return this.$message.error(success.meta.msg)
      }
      // 把 回调信息里面的图片路径 存在 pics中 格式参考 接口文档
      var obj = { pic: success.data.tmp_path }
      this.AddForm.pics.push(obj)
      // console.log(this.AddForm.pics)
    },
    // 图片列表 移除图片的回调处理
    handleRemove (delInfo) {
      // console.log(delInfo, 2)
      // 过滤掉删除掉的那张图片的地址
      this.AddForm.pics = this.AddForm.pics.filter(
        item => item.pic !== delInfo.response.data.tmp_path
      )
      // console.log(this.AddForm.pics)
    },
    // 获取级联器数据
    async getJiList () {
      var { data: dt } = await this.$http.get('categories')
      // console.log(dt)
      this.jiInfo = dt.data // 把数据赋值给级联器上级数据来源
    },
    handleChange () {
      // console.log(this.AddForm.sanjiCat)
      var len = this.AddForm.sanjiCat.length
      if (len === 3) {
        // 如果长度为3 说明选择了三级分类 把三级分类的ID存起来
        this.selectCatId = this.AddForm.sanjiCat[2]
        // 把各个级别分类的id 由数组转换成字符串形式  看文档要求
        this.AddForm.goods_cat = this.AddForm.sanjiCat.join(',')
      } else {
        // 恢复默认值
        this.selectCatId = 0
        this.AddForm.goods_cat = '' // 恢复默认
      }
    },
    // 标签切换之前的处理
    beforeLeave () {
      if (this.selectCatId === 0) {
        // 判断 this.selectCatId === 0 说明没有选择三级分类
        this.$message.error('请选择三级分类')
        return false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px;
}
.el-button {
  margin-top: 15px;
}
</style>
